package com.qq2008.game.stzb.interceptor;


import com.qq2008.game.stzb.annotation.AuthPassport;
import com.qq2008.game.stzb.conf.ServerConf;
import com.qq2008.game.stzb.jdo.User;
import com.qq2008.game.stzb.service.UserService;
import com.qq2008.game.stzb.utils.CookieUtil;
import com.qq2008.game.stzb.utils.HashUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

// 实现自动登陆
public class AutoLoginInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //
        HttpSession session = request.getSession();
        // 获取cookie中存储的关于自动登录的数据
        String hashID = CookieUtil.getValue(request, "uuid");
        String hash = CookieUtil.getValue(request, "hash");
        // 使用解密后的id从数据库拿到相关用户
        // 用相关用户的某些字段加密后和cookie中存储的信息对比正确后实存至session
        User user = (User) session.getAttribute("user");
        if (!StringUtils.isEmpty(hashID) && !StringUtils.isEmpty(hash) && user == null) {
            String uuid = HashUtil.desDecode(hashID);
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("unionID", uuid);
            param.put("checkFlag", "unionID");
            user = userService.get(param);
            if (hash.equals(HashUtil.toMd5(user.getLoginName() + "," + user.getPassword()))) {
                session.setAttribute("user", user);
            }
        }

        // 登录注解验证
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        AuthPassport authPassport = handlerMethod.getMethodAnnotation(AuthPassport.class);
        if (null != authPassport && null == user) {
            String url = request.getRequestURL().toString();
            String queryString = request.getQueryString();
            if (!StringUtils.isEmpty(queryString)) {
                url += "?" + queryString;
            }
            session.setAttribute("returnUrl", url);
            response.sendRedirect(ServerConf.HOST_LOGIN);
            return false;
        }

        return true;
    }

}
